package org.ee.system.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.ee.core.api.PageResult;
import org.ee.core.api.Result;
import org.ee.system.dto.UserDto;
import org.ee.system.service.UserService;
import org.ee.system.vo.UserInfoVo;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

/**
 * 用户数据接口
 */
@RestController
@RequestMapping("/user")
@Tag(name="用户管理",description = "用户管理模块")
public class UserController {
    private final UserService userSeriice;

    public UserController(UserService userSeriice) {
        this.userSeriice = userSeriice;
    }

    /**
     *
     * @param userDto
     * @return
     */
    @Operation(summary = "添加")
    @PostMapping("/add")
    public Result<Void> add(UserDto userDto){
        try{
            userSeriice.add(userDto);
            return Result.success();
        }catch (Exception e){
            return Result.failure(e.getMessage());
        }
    }
    /**
     * 获取当前用户信息
     *
     * @return
     */
    @GetMapping("/info")
    @Operation(description = "获取当前用户信息",security = {@SecurityRequirement(name = "BearerAuth")})
    public Result<UserInfoVo> getSysUserInfo() {
        return Result.success(userSeriice.getCurrentUserInfo());
    }

    /**
     * 分页获取用户列表
     *
     * @return
     */
    @GetMapping("/page")
    public Result<PageResult<UserInfoVo>> getSysUsers(@RequestParam(value = "current") Integer current,
                                                      @RequestParam(value = "size") Integer size) {
        return Result.success(userSeriice.getSysUserList(current, size));
    }

    /**
     * 退出方法
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            // 如果是有状态，就从 Redis 删除
            // redisTemplate.delete("login:token:" + token);
        }
        SecurityContextHolder.clearContext();
        return Result.success();
    }

    @Operation(summary = "删除")
    @DeleteMapping("/delete/{id}")
    public Result<Void> delete(@PathVariable("id") Long id) {
        try{
            userSeriice.delete(id);
            return Result.success();
        }catch (Exception e){
            return Result.failure(e.getMessage());
        }
    }
}
